package estore.view;

import estore.model.Product;
import estore.service.ProductService;
import estore.service.ProductSorters;
import java.io.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class ConsoleShop {
    private final ProductService productService = new ProductService();
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    public void start() {
        try {
            while (true) {
                showMenu();
                int choice = scanner.nextInt();
                scanner.nextLine();
                switch (choice) {
                    case 1:
                        browseProducts();
                        break;
                    case 2:
                        addToCart();
                        break;
                    case 3:
                        viewCart();
                        break;
                    case 4:
                        showSortedProducts();
                        break;
                    case 99:
                        backupData();
                        break;
                    case 5:
                        saveDataBeforeExit();
                        System.out.println("感谢使用，再见！");
                        return;
                    default:
                        System.out.println("无效的选项，请重新输入！");
                }
            }
        } catch (Exception e) {
            System.err.println("程序异常：" + e.getMessage());
        } finally {
            scanner.close();
        }
    }

    private void saveDataBeforeExit() {
        try {
            productService.saveData();
        } catch (IOException e) {
            System.err.println("保存失败：" + e.getMessage());
            System.out.print("是否强制退出（Y/N）：");
            String confirm = scanner.nextLine();
            if (!"Y".equalsIgnoreCase(confirm)) {
                start();
            }
        }
    }

    private void backupData() {
        String sourcePath = productService.getDataFilePath();
        File sourceFile = new File(sourcePath);
        if (!sourceFile.exists()) {
            System.err.println("源文件不存在：" + sourcePath);
            return;
        }
        String backupPath = sourcePath + ".bak";
        File backupFile = new File(backupPath);
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(backupFile))) {
            byte[] buffer = new byte[1024];
            int len;
            System.out.println("正在备份...");
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            bos.flush();
            System.out.println("备份成功：" + backupPath);
        } catch (IOException e) {
            System.err.println("备份失败：" + e.getMessage());
            if (backupFile.exists()) backupFile.delete();
        }
    }

    private void showMenu() {
        System.out.println("\n ----欢迎来到商城---- ");
        System.out.println("1. 浏览所有商品");
        System.out.println("2. 添加商品到购物车");
        System.out.println("3. 查看购物车");
        System.out.println("4. 自定义排序浏览商品");
        System.out.println("5. 退出");
        System.out.println("（管理员功能：输入99可备份数据）");
        System.out.print("请输入您的选择: ");
    }

    private void showSortedProducts() {
        System.out.println("\n--- 排序方式 ---");
        System.out.println("1. 价格从低到高");
        System.out.println("2. 价格从高到低");
        System.out.println("3. 库存从多到少");
        System.out.println("4. 按商品ID排序");
        System.out.print("选择：");
        int choice = scanner.nextInt();
        scanner.nextLine();
        switch (choice) {
            case 1:
                browseProducts(ProductSorters.BY_PRICE_ASC);
                break;
            case 2:
                browseProducts(ProductSorters.BY_PRICE_DESC);
                break;
            case 3:
                browseProducts(ProductSorters.BY_STOCK_DESC);
                break;
            default:
                browseProducts(Comparator.comparing(Product::getId));
        }
    }

    private void browseProducts(Comparator<Product> comparator) {
        System.out.println("\n--- 商品列表 ---");
        List<Product> products = new ArrayList<>(productService.getAllProducts());
        if (products.isEmpty()) {
            System.out.println("无商品");
            return;
        }
        products.sort(comparator);
        products.forEach(System.out::println);
    }

    private void browseProducts() {
        browseProducts(Comparator.comparing(Product::getId));
    }

    private void addToCart() {
        System.out.print("商品ID：");
        String productId = scanner.nextLine();
        Product product = productService.findProductById(productId);
        if (product == null) {
            System.out.println("商品不存在！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("商品售罄！");
            return;
        }
        System.out.print("购买数量：");
        int quantity = scanner.nextInt();
        scanner.nextLine();
        if (quantity <= 0) {
            System.out.println("数量必须为正数！");
            return;
        }
        if (quantity > product.getStock()) {
            System.out.println("库存不足（当前：" + product.getStock() + "）");
            return;
        }
        shoppingCart.put(productId, shoppingCart.getOrDefault(productId, 0) + quantity);
        System.out.println("添加成功：" + product.getName());
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车为空");
            return;
        }
        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            Product product = productService.findProductById(entry.getKey());
            double subtotal = product.getPrice() * entry.getValue();
            System.out.printf("商品：%-20s | 单价：¥%-8.2f | 数量：%-3d | 小计：¥%.2f\n",
                    product.getName(), product.getPrice(), entry.getValue(), subtotal);
            total += subtotal;
        }
        System.out.printf("总计：¥%.2f\n", total);
    }

    public static void main(String[] args) {
        new ConsoleShop().start();
    }
}